package com.mediacloud.app.newsmodule.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.eventTrack.DataCollectRequestButtonClickExpansion
import com.mediacloud.app.assembly.util.load
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.utils.spider.FollowKit
import com.mediacloud.app.newsmodule.utils.spider.IAttentionCall
import com.mediacloud.app.newsmodule.utils.spider.SpiderKit
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.user.model.UserInfo
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.zimeiti.controler.ZiMeiTiDetailController
import com.zimeiti.details.MediaAuthorDetailActivity
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_number_school.*
import kotlinx.android.synthetic.main.simple_title_bar_dark_tx.*
import org.json.JSONObject
import retrofit2.Response

class NumberSchoolActivity : BaseBackActivity(), OnRefreshLoadMoreListener {
    var page: Int = 1
    var adapter: Adapter? = null
    var ziMeiTiDetailController: ZiMeiTiDetailController? = null
    override fun getLayoutResID(): Int {
        return R.layout.activity_number_school
    }

    override fun getStatusBarColor()= Color.WHITE
    override fun showTitleBar()=false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        backIv.setOnClickListener { this }
        refreshLayout.setOnRefreshLoadMoreListener(this)
        ziMeiTiDetailController = ZiMeiTiDetailController()
        recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = Adapter()
        recyclerView.adapter = adapter
        getData()
        adapter?.setOnItemChildClickListener { adapter, view, position ->
            val item = adapter.data[position] as NumberSchool
            if (view.id == R.id.image_is_attention) {
                view.isClickable = false

                FollowKit.followOrNot(null,this@NumberSchoolActivity, item.userId, item.userNickName,object : IAttentionCall {
                    override fun onAttentionResult(attention: Boolean) {

                        view.isClickable = true
                        adapter?.notifyItemChanged(position)
                    }

                    override fun onAttentionFail() {
                        view.isClickable = true
                    }
                },null)
                val userInfo = UserInfo.getUserInfo(this@NumberSchoolActivity)
                if (userInfo.isLogin) {
                    val operate = if (!item.isFollowed) DataCollectRequestButtonClickExpansion.POSITIVE_ACTION else DataCollectRequestButtonClickExpansion.NEGATIVE_ACTION
                    DataCollectRequestButtonClickExpansion.operateMeidaAttention(
                        NumberSchoolActivity::class.java.name,
                        item.userId,
                        item.userNickName,
                        operate,
                        userInfo.userid,
                        userInfo.nickname
                    )
                }
            }
        }
        adapter?.setOnItemClickListener { adapter, _, position ->
            val item = adapter.data[position] as NumberSchool
            val intent = Intent(this, MediaAuthorDetailActivity::class.java)
            intent.putExtra("author_id", item.userId)
            startActivity(intent)
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        page = 1
        getData()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        page++
        getData()
    }

    fun getData() {
        DataInvokeUtil.ziMeiTiApi.getNumberSchool(page)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<Response<JSONObject>> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: Response<JSONObject>) {
                    refreshLayout.finishRefresh()
                    refreshLayout.finishLoadMore()
                    t.body()?.let {
                        if (it.optBoolean("state")) {
                            it.optJSONObject("data").let {
                                val metas = it.optJSONArray("meta")
                                val size = metas.length()
                                val dataList: MutableList<NumberSchool> = ArrayList()
                               // val ids: MutableList<String> = ArrayList()
                                for (i in 0 until size) {
                                    val meta =metas.optJSONObject(i)
                                    val userId = meta.optString("userId")
                                  //  ids.add(userId)
                                    dataList.add(
                                        NumberSchool(
                                           userId,
                                            meta.optString("userAccount"),
                                            meta.optString("userNickName"),
                                            meta.optString("userName"),
                                            meta.optString("userImage"),
                                            meta.optString("description"),
                                        )
                                    )
                                }

                             //   SpiderKit.refreshAttentionStatus(this@NumberSchoolActivity,ids,adapter)
                                if (page == 1) {
                                    adapter?.setNewData(dataList)
                                } else {
                                    adapter?.addData(dataList)
                                }
                                it.optJSONObject("paging")?.let {
                                    refreshLayout.setNoMoreData(page >= it.optInt("lastPage"))
                                }
                            }
                        }
                    }
                }

                override fun onError(e: Throwable) {
                    refreshLayout.finishRefresh()
                    refreshLayout.finishLoadMore()
                }

                override fun onComplete() {
                }

            })
    }


    inner class Adapter : BaseQuickAdapter<NumberSchool, BaseViewHolder>(R.layout.x_subscribe_more_item_army) {
        @SuppressLint("SetTextI18n")
        override fun convert(helper: BaseViewHolder, item: NumberSchool?) {
            val iconImage = helper.getView<ImageView>(R.id.image_my_subscribe_content_icon)
            val titleTv = helper.getView<TextView>(R.id.tv_my_subscribe_content_title)
            val summaryTv = helper.getView<TextView>(R.id.tv_summary)
            val addAttentionImage = helper.getView<TextView>(R.id.image_is_attention)
            helper.addOnClickListener(R.id.image_is_attention)
            item?.let {
                if (it.userImage == "0" || TextUtils.isEmpty(it.userImage)) {
                    iconImage.setImageResource(R.drawable.new_user_logo_login)
                } else {
                    iconImage.load(it.userImage)
                }
                titleTv.text = it.userName
                summaryTv.text = it.description
                val attention = it.isFollowed
                addAttentionImage.isSelected = attention
                if (attention) {
                    addAttentionImage.text = "已关注"
                } else {
                    addAttentionImage.text = "关注"
                }
            }
        }

    }


}